//
//  NetworkRequest.m
//  封装网络请求
//
//  Created by dllo on 15/10/1.
//  Copyright © 2015年 LuckyHan. All rights reserved.
//

#import "NetworkRequest.h"

@implementation NetworkRequest

#pragma mark 网络请求
+ (void)getDataWithURLString:(NSString *)urlString BodyString:(NSString *)bodyString DataBlock:(void (^)(id))dataBlock
{
    urlString = [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:urlString]];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain", @"text/json", @"application/json", @"text/javascript", @"text/html", @"application/javascript", @"application/x-javascript", @"text/js", nil];
    if (!bodyString) {
//        [manager GET:urlString parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
//            dataBlock(responseObject);
//        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//            NSLog(@"网络请求失败");
//        }];
        [manager GET:urlString parameters:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
            dataBlock(responseObject);
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//            NSLog(@"网络请求失败");
        }];
    } else {
//        [manager POST:urlString parameters:[self getDictionaryWithBodyString:bodyString] success:^(AFHTTPRequestOperation *operation, id responseObject) {
//            dataBlock(responseObject);
//        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//            NSLog(@"网络请求失败");
//        }];
        [manager POST:urlString parameters:[self getDictionaryWithBodyString:bodyString] success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
            dataBlock(responseObject);
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//            NSLog(@"网络请求失败");
        }];
    }
}

#pragma mark 得到bodyString的字典
+ (NSMutableDictionary *)getDictionaryWithBodyString:(NSString *)bodyString
{
    NSMutableDictionary *bodyDictionary = [NSMutableDictionary dictionary];
    if (![bodyString containsString:@"&"]) {
        NSArray *arr = [bodyString componentsSeparatedByString:@"="];
        [bodyDictionary setObject:arr[1] forKey:arr[0]];
        return bodyDictionary;
    }
    NSArray *array = [bodyString componentsSeparatedByString:@"&"];
    for (NSString *str in array) {
        NSArray *arr = [str componentsSeparatedByString:@"="];
        [bodyDictionary setObject:arr[1] forKey:arr[0]];
    }
    return bodyDictionary;
}

#pragma mark 下载文件
+ (void)downloadFileWithURLString:(NSString *)urlString
                     WithFileName:(NSString *)fileName
                         Progress:(void (^)(float progress))progress
                          Success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
                          Failure:(void (^)(AFHTTPRequestOperation *operation, NSError *erro))failure
{
    //保存在Documents里的文件夹
    NSString *folderPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:@"music"];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    //如果文件夹不存在, 创建文件夹
    if (![fileManager fileExistsAtPath:folderPath]) {
        [fileManager createDirectoryAtPath:folderPath withIntermediateDirectories:YES attributes:nil error:nil];
//        NSLog(@"创建文件夹");
    }
    
    AFHTTPRequestSerializer *serializer = [AFHTTPRequestSerializer serializer];
    NSMutableURLRequest *request = [serializer requestWithMethod:@"GET" URLString:urlString parameters:nil error:nil];
    
    //单个文件绝对路径
    NSString *absolutePath = [folderPath stringByAppendingPathComponent:fileName];
    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    [operation setOutputStream:[NSOutputStream outputStreamToFileAtPath:absolutePath append:NO]];
    
    //下载过程
    [operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
        float currentProgress = (float)totalBytesRead / totalBytesExpectedToRead;
        progress(currentProgress);
//        NSLog(@"已下载: %f", currentProgress);
    }];
    
    //下载结果
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
//        NSLog(@"文件夹路径: %@", folderPath);
//        NSLog(@"下载成功");
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//        NSLog(@"文件夹路径: %@", folderPath);
//        NSLog(@"下载失败");
    }];
    
    [operation start];
}

@end
